package {

import com.adobe.serialization.json.JSON;

import components.AreaItem;
import components.MapScroller;

import core.Facade;
import core.GameGroup;
import core.ALevel;
import core.MovingObject;

import events.AreaSelectedEvent;

import flash.display.Bitmap;
import flash.display.InteractiveObject;
import flash.display.Shape;
import flash.events.Event;
import flash.utils.Dictionary;


import ru.cjay.loading.JSONLoader;

import ru.cjay.loading.ResourceManager;
import ru.cjay.loading.SWFAssetList;

import utils.TraceObject;


public class MapLevel extends ALevel {
    private var _map:MapScroller;
    public var _regions:GameGroup;
    public var _untouch_regions:GameGroup;
    private var _region_map:Dictionary = new Dictionary();
    private var _lastRegion:AreaItem;

    private var assets_list:Object;


    public function MapLevel() {
        super();
//        _updateTimer = new Timer(3000, 1);
        rlist = new Object();

        rlist["background"] = "http://vd.osa-corp.ru/i/vday/map/paper.jpg";
        rlist["map"] = "http://vd.osa-corp.ru/i/vday/map/big_map.jpg";
        rlist["message_box"] = "http://vd.osa-corp.ru/i/vday/map/messageBox.png";

        swf_list = new Array();

//        var m_asset:SWFAssetList = new SWFAssetList("main_assets","http://vd.osa-corp.ru/i/vday/map/assets_main.swf");
        var m_asset:SWFAssetList = new SWFAssetList("main_assets","http://vd.osa-corp.ru/i/vday/map/assets_main.swf");
        m_asset.addAsset("plane_left","mc_PlaneLeftGroup1");
        m_asset.addAsset("plane_right","mc_PlaneRightGroup1");
        m_asset.addAsset("clouds","mv_Clouds");
        swf_list.push(m_asset);

        m_asset = new SWFAssetList("ui","http://vd.osa-corp.ru/i/vday/map/ui.swf");
        m_asset.addAsset("ZoneBaloon","ZoneBaloon");
        m_asset.addAsset("BigHint","BigHint");
        m_asset.addAsset("LittleHint","LittleHint");
        m_asset.addAsset("InfoWindow","InfoWindow");
        m_asset.addAsset("ZoneHint","ZoneHint");
        m_asset.addAsset("DependenciesLine","DependenciesLine");
        m_asset.addAsset("FriendScrollPanel","FriendScrollPanel");
        m_asset.addAsset("FriendIcon","FriendIcon");
        m_asset.addAsset("FriendIcon","FriendIcon");
        m_asset.addAsset("CheckBox","CheckBox");
        m_asset.addAsset("DropRow","DropRow");
        m_asset.addAsset("WinWindow","WinWindow");
        m_asset.addAsset("LooseWindow","LooseWindow");
        m_asset.addAsset("FlashPopup","FlashPopup");


        swf_list.push(m_asset);

        m_asset = new SWFAssetList("icons","http://vd.osa-corp.ru/i/vday/map/icons.swf");
        m_asset.addAsset("1","IconTeaching");
        m_asset.addAsset("2","IconCamp");
        m_asset.addAsset("3","IconTruck");
        m_asset.addAsset("4","IconSpy");
        m_asset.addAsset("5","IconSubmarine");
        m_asset.addAsset("6","IconTankers");
        swf_list.push(m_asset);

    }


    override public function create():void {
        trace("MapLevel create");
        loadResources("http://vd.osa-corp.ru/map/zones?" + Facade.getInstance().authUrlParams());
    }

    override protected function parse_config(config:Object):void {
        trace("MapLevel parseConfig");
        var res:Object = ResourceManager.getInstance().getResourceByName("map");
        var back:Bitmap = res as Bitmap;

        var back_canv:Bitmap = ResourceManager.getInstance().getResourceByName("background") as Bitmap;

        _map = new MapScroller(back);
        _map.width = 668 - 30;
        _map.height = 668 - 30;
        _map.recalc();          // recalculate size of component
        _map.x = 15;
        _map.y = 15;

        addGameObject(_map);
        _regions = new GameGroup();
        _untouch_regions = new GameGroup()

        addGameObject(_regions);
        addGameObject(_untouch_regions);


        var object:Object;
        var areaItem:AreaItem;
        _region_map = new Dictionary();
        for each(object in config.data.zones) {
            areaItem = new AreaItem(object);
            _regions.addObject(areaItem);
            _region_map[String(areaItem.zone_id)] = areaItem;

            areaItem.x = object.x ? object.x : Math.floor(Math.random() * (1 + Facade.getInstance().MAXWIDTH - 300)) + 30;
            areaItem.y = object.y ? object.y : Math.floor(Math.random() * (1 + Facade.getInstance().MAXHEIGHT - 300)) + 30;

            areaItem.addEventListener(AreaSelectedEvent.AREA_SELECT, onSelectRegion);
        }


        var cloudsClass:Class = ResourceManager.getInstance().getSwfAssetClass("main_assets:clouds") as Class;
        var clouds:InteractiveObject  = new cloudsClass();
        clouds.alpha = 0.8;
        var movingCloud:MovingObject = new MovingObject(clouds);
        movingCloud.setBounds(-700,-1200,2000,1500);
        movingCloud.setPos(200,-300);
        movingCloud.setSpeed(-0.4,-0.1);
        _untouch_regions.addChild(movingCloud);
        addUpdatableObject(movingCloud);


        var clouds = new cloudsClass();
        clouds.alpha = 0.8;
        movingCloud = new MovingObject(clouds);
        movingCloud.setBounds(-700,-1200,2000,1500);
        movingCloud.setPos(1105,600);
        movingCloud.setSpeed(-0.5,-0.3);
        _untouch_regions.addChild(movingCloud);
        addUpdatableObject(movingCloud);

         var clouds = new cloudsClass();
        clouds.alpha = 0.8;
         movingCloud = new MovingObject(clouds);
        movingCloud.setBounds(-700,-1200,2000,1500);
        movingCloud.setPos(1995,1490);
        movingCloud.setSpeed(-0.4,-0.2);
        _untouch_regions.addChild(movingCloud);
        addUpdatableObject(movingCloud);

//        airplanes
        var PlanesLeftClass:Class = ResourceManager.getInstance().getSwfAssetClass("main_assets:plane_left") as Class;
        var planes_left:InteractiveObject = new PlanesLeftClass();
        movingCloud = new MovingObject(planes_left);
        movingCloud.setBounds(-700,-1200,2000,1500);
        movingCloud.setPos(1995,1490);
        movingCloud.setSpeed(-1,-5);
        _untouch_regions.addChild(movingCloud);
        addUpdatableObject(movingCloud);

        planes_left = new PlanesLeftClass();
         movingCloud = new MovingObject(planes_left);
        movingCloud.setBounds(-700,-1200,2000,1500);
        movingCloud.setPos(1000,700);
        movingCloud.setSpeed(-1,-5);
        _untouch_regions.addChild(movingCloud);
        addUpdatableObject(movingCloud);

        planes_left = new PlanesLeftClass();
         movingCloud = new MovingObject(planes_left);
        movingCloud.setBounds(-700,-1200,2000,1500);
        movingCloud.setPos(-500,-600);
        movingCloud.setSpeed(-1,-5);
        _untouch_regions.addChild(movingCloud);
        addUpdatableObject(movingCloud);


        var PlanesRighttClass:Class = ResourceManager.getInstance().getSwfAssetClass("main_assets:plane_right") as Class;
        var planes_right:InteractiveObject = new PlanesRighttClass();
        movingCloud = new MovingObject(planes_right);
        movingCloud.setBounds(-700,-1200,2000,1500);
        movingCloud.setPos(1995,1490);
        movingCloud.setSpeed(2,-4);
        _untouch_regions.addChild(movingCloud);
        addUpdatableObject(movingCloud);

        planes_right = new PlanesRighttClass();
        movingCloud = new MovingObject(planes_right);
        movingCloud.setBounds(-700,-1200,2000,1500);
        movingCloud.setPos(1100,700);
        movingCloud.setSpeed(2,-4);
        _untouch_regions.addChild(movingCloud);
        addUpdatableObject(movingCloud);

        planes_right = new PlanesRighttClass();
        movingCloud = new MovingObject(planes_right);
        movingCloud.setBounds(-700,-1200,2000,1500);
        movingCloud.setPos(200,-200);
        movingCloud.setSpeed(2,-4);
        _untouch_regions.addChild(movingCloud);
        addUpdatableObject(movingCloud);


        _untouch_regions.mouseChildren = false;
        _untouch_regions.mouseEnabled = false;

        var rectMask:Shape = new Shape();

        rectMask.graphics.beginFill(0x000000, 1);
        rectMask.graphics.drawRect(0, 0, 668, 668);
        rectMask.graphics.drawRect(15, 15, 638, 638);
        rectMask.graphics.endFill();

        addChild(rectMask);
        addChild(back_canv);

        back_canv.mask = rectMask;
        rectMask.cacheAsBitmap = true;
        back_canv.cacheAsBitmap = true;


        updateMap();
    }

    override public function deactivate():void {
        trace("MapLevel deactivate");
        freeze();
        super.deactivate();

    }

    override public function activate():void {
        trace("MapLevel activate");
        super.activate();
        unfreeze();


    }

    public function freeze():void {
        trace("MapLevel freeze");
//        _updateTimer.stop();
//        _updateTimer.removeEventListener(TimerEvent.TIMER, updateMap);
    }

    public function unfreeze():void {
        trace("MapLevel unfreeze");
//        _updateTimer.addEventListener(TimerEvent.TIMER, updateMap);
//        _updateTimer.start();
    }

    private function updateMap(evetn:Event = null):void {
        //var request:URLRequest = new URLRequest("/refresh_main.txt");
        //var args:URLVariables = new URLVariables();

        //args.cachebuster =   new Date().getTime();
        //request.data = args;
        //SafeConnection.getInstance().makeSafe(request,onMapRefresh);
        onMapRefresh(null);
    }

    private function onMapRefresh(event:Event):void {
        if (event != null) {
            var rawData:String = event.target.data;
            var response:Object = JSON.decode(rawData);

            var object:Object;
            for (object in response.levels) {
//            trace("K. #1:\n");
//            trace(TraceObject.traceObject(response.levels[object]));


                if (response.levels[object]) {    // К. Добавил проверку потому, что тут в первый раз запуска выскакивает ошибка 0_о
                    if (_region_map[String(response.levels[object].id)]) {
                        _region_map[String(response.levels[object].id)].session_key = response.levels[object].session_key;
                    }
                }
            }
        }

//        _updateTimer.reset();
//        _updateTimer.start();

    }


    private function onSelectRegion(event:Event):void {
        Facade.getInstance().fadeIn(true);

        var region:AreaItem = event.target as AreaItem;
        if ((region != null) && (region != _lastRegion)) {
            _lastRegion = region;
        }
//        loading info from this level
        var url:String = "http://vd.osa-corp.ru/map/gamezone?" + Facade.getInstance().authUrlParams() + "&zone_id=" + region.zone_id;
        var loader:JSONLoader = new JSONLoader();
        loader.loadJSON(url, getZoneInfo);

    }

    private function getZoneInfo(obj:Object):void {

        if (obj.data.is_open == 1) {
//            trace("Loooook here ->", obj.data.strings.user_count_suf);
            _lastRegion.fillAdditionInformation(obj.data);
            _lastRegion.PlayThisLevel();
        }
        else {
            trace("This level is not opened 0_o");
            trace(TraceObject.traceObject(obj));
        }
    }

    override public function update():void {
        if (_regions) {
            _regions.x = _map.offset_x;
            _regions.y = _map.offset_y;
        }
        if (_untouch_regions) {
            _untouch_regions.x = _map.offset_x;
            _untouch_regions.y = _map.offset_y;
        }
        super.update();
    }

    public function get lastRegion():AreaItem {
        return _lastRegion;
    }

    public function set lastRegion(value:AreaItem):void {
        _lastRegion = value;
    }
}
}
